package com.example.starter.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

import java.util.Map;


/**
 * @author 王令
 * @since 2022/9/19 8:41
 */
public class JSONUtil {

    private static final ObjectMapper instance;

    static {
        instance = new ObjectMapper();
    }

    @SneakyThrows
    public static String toJsonStr(Object o) {
        return instance.writeValueAsString(o);
    }

    @SneakyThrows
    public static byte[] toJsonByte(Object o) {
        return instance.writeValueAsBytes(o);
    }

    @SneakyThrows
    public static <T> T parse(String json, Class<T> clazz) {
        return instance.readValue(json, clazz);
    }

    @SneakyThrows
    public static <T> T parse(byte[] bytes, Class<T> clazz) {
        return instance.readValue(bytes, clazz);
    }

    @SneakyThrows
    public static Map<String, Object> parseToObjMap(String json) {
        return instance.readValue(json, new TypeReference<Map<String, Object>>() {});
    }

    @SneakyThrows
    public static Map<String, String> parseToStrMap(String json) {
        return instance.readValue(json, new TypeReference<Map<String, String>>() {});
    }

}
